package com.centaline.androidsalesblog.fragments.calculate;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.SwitchCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.RelativeLayout;

import com.centaline.androidsalesblog.R;
import com.centaline.androidsalesblog.base.BaseTaxCalFragment;
import com.centaline.androidsalesblog.constants.ExtraConstant;
import com.centaline.androidsalesblog.model.businissobject.TaxCalculateBo;
import com.jakewharton.rxbinding.widget.RxTextView;
import com.orhanobut.logger.Logger;
import com.trello.rxlifecycle.FragmentEvent;

import java.util.Locale;

import rx.Observable;
import rx.functions.Action1;
import rx.functions.Func2;
import rx.functions.Func3;

/**
 * 二手房税费计算器
 * Created by Ruan on 2016/3/3.
 */
public class EsfSaleCalcFragment extends BaseTaxCalFragment implements View.OnClickListener {

    private RelativeLayout rl_house_type, rl_levy_type, rl_buy_years, rl_house_original;
    private AppCompatEditText aet_house_area, aet_house_unit_price, aet_house_total, aet_house_original;
    private AppCompatTextView atv_house_type, atv_levy_type, atv_buy_years, atv_buy_yes_no, atv_sale_yes_no;
    private SwitchCompat sc_seller_only, sc_buyer_first;
    private Button btn_tax_fragment;

    private final String[] houseTypes = new String[]{"普通住宅", "非普通住宅"};
    private final String[] levyTypes = new String[]{"总价", "差价"};
    private final String[] buyYears = new String[]{"2年以内", "2-5年", "5年以上"};
    private AlertDialog houseTypeDialog;//房屋类型
    private AlertDialog levyTypeDialog;//征收方式
    private AlertDialog buyYearsDialog;//购置年限
    private int houseType;
    private int levyType;
    private int buyYear;

    @Override
    protected int setLayoutId() {
        return R.layout.fragment_calc_sale_esf;
    }

    @Override
    protected void findViews(View view) {

        rl_house_type = (RelativeLayout) view.findViewById(R.id.rl_house_type);
        atv_house_type = (AppCompatTextView) view.findViewById(R.id.atv_house_type);
        aet_house_area = (AppCompatEditText) view.findViewById(R.id.aet_house_area);
        aet_house_unit_price = (AppCompatEditText) view.findViewById(R.id.aet_house_unit_price);
        aet_house_total = (AppCompatEditText) view.findViewById(R.id.aet_house_total);
        rl_levy_type = (RelativeLayout) view.findViewById(R.id.rl_levy_type);
        atv_levy_type = (AppCompatTextView) view.findViewById(R.id.atv_levy_type);
        rl_buy_years = (RelativeLayout) view.findViewById(R.id.rl_buy_years);
        atv_buy_years = (AppCompatTextView) view.findViewById(R.id.atv_buy_years);
        rl_house_original = (RelativeLayout) view.findViewById(R.id.rl_house_original);
        aet_house_original = (AppCompatEditText) view.findViewById(R.id.aet_house_original);
        sc_buyer_first = (SwitchCompat) view.findViewById(R.id.sc_buyer_first);
        atv_buy_yes_no = (AppCompatTextView) view.findViewById(R.id.atv_buy_yes_no);
        sc_seller_only = (SwitchCompat) view.findViewById(R.id.sc_seller_only);
        atv_sale_yes_no = (AppCompatTextView) view.findViewById(R.id.atv_sale_yes_no);
        btn_tax_fragment = (Button) view.findViewById(R.id.btn_tax_fragment);

    }

    @Override
    protected void initView() {

        rl_house_type.setOnClickListener(this);
        rl_levy_type.setOnClickListener(this);
        rl_buy_years.setOnClickListener(this);
        aet_house_area.requestFocus();

        sc_buyer_first.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                atv_buy_yes_no.setText(isChecked ? "是" : "否");
            }
        });
        sc_seller_only.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                atv_sale_yes_no.setText(isChecked ? "是" : "否");
            }
        });

        Observable<CharSequence> houseAreaObservable = RxTextView.textChanges(aet_house_area);
        Observable<CharSequence> housePreObservable = RxTextView.textChanges(aet_house_unit_price);
        Observable<CharSequence> totalPriceObservable = RxTextView.textChanges(aet_house_total);
        Observable<CharSequence> originObservable = RxTextView.textChanges(aet_house_original);

        //计算总价
        Observable.combineLatest(houseAreaObservable, housePreObservable, new Func2<CharSequence, CharSequence, CharSequence>() {
            @Override
            public CharSequence call(CharSequence charSequence, CharSequence charSequence2) {
                if (TextUtils.isEmpty(charSequence) || TextUtils.isEmpty(charSequence2)) {
                    return "";
                } else {
                    double insert1 = Double.parseDouble(charSequence.toString());
                    double insert2 = Double.parseDouble(charSequence2.toString());
                    return String.format(Locale.CHINA, "%.0f", insert1 * insert2 / 10000);
                }
            }
        }).compose(this.<CharSequence>bindUntilEvent(FragmentEvent.DESTROY))
                .subscribe(new Action1<CharSequence>() {
                    @Override
                    public void call(CharSequence charSequence) {
                        aet_house_total.setText(charSequence);
                    }
                });

        Observable.combineLatest(totalPriceObservable, originObservable,
                new Func2<CharSequence, CharSequence, Boolean>() {
                    @Override
                    public Boolean call(CharSequence charSequence, CharSequence charSequence2) {
                        Logger.d("charSequence : %s charSequence2 : %s", charSequence, charSequence2);
                        return charSequence.toString().equals(charSequence2.toString()) && !(TextUtils.isEmpty(charSequence));
                    }
                }).compose(this.<Boolean>bindUntilEvent(FragmentEvent.DESTROY))
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean aBoolean) {
                        if (aBoolean) {
                            toast("你的房屋没有差价,请重新填写");
                        }
                    }
                });

        Observable.combineLatest(houseAreaObservable, totalPriceObservable, originObservable,
                new Func3<CharSequence, CharSequence, CharSequence, Boolean>() {
                    @Override
                    public Boolean call(CharSequence charSequence, CharSequence charSequence2, CharSequence charSequence3) {
                        if (levyType == 1) {
                            return !(TextUtils.isEmpty(charSequence) || TextUtils.isEmpty(charSequence2));
                        } else {
                            return !(TextUtils.isEmpty(charSequence) ||
                                    TextUtils.isEmpty(charSequence2) ||
                                    TextUtils.isEmpty(charSequence3) ||
                                    charSequence2.equals(charSequence3));
                        }
                    }
                }).compose(this.<Boolean>bindUntilEvent(FragmentEvent.DESTROY))
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean aBoolean) {
                        btn_tax_fragment.setEnabled(aBoolean);
                    }
                });

        setCalcClick(btn_tax_fragment);
        super.initView();

        Bundle bundle = getArguments();
        if (bundle != null) {
            double price = bundle.getDouble(ExtraConstant.TAX_DAN_PRICE, 0);
            double area = bundle.getDouble(ExtraConstant.Area, 0);
            double total_price = bundle.getDouble(ExtraConstant.TAX_TOTAL_PRICE, 0);
            if (price > 0 && area > 0) {
                aet_house_area.setText(String.format(Locale.CHINA, "%.0f", area));
                aet_house_unit_price.setText(String.format(Locale.CHINA, "%.0f", price));
                aet_house_total.setText(String.format(Locale.CHINA, "%.0f", total_price/10000));
            }
        }
    }

    @Override
    protected void initData() {
        houseType = 1;
        levyType = 1;
        buyYear = 2;
    }

    @Override
    protected void startCalculate() {

        TaxCalculateBo taxCalculateBo = new TaxCalculateBo();
        taxCalculateBo.setModeType(1);
        taxCalculateBo.setHouseType(houseType);
        taxCalculateBo.setHouseArea(Double.parseDouble(aet_house_area.getText().toString()));
        if (aet_house_unit_price.getText().length() > 0) {
            taxCalculateBo.setHouseUnitPrice(Double.parseDouble(aet_house_unit_price.getText().toString()));
        }
        taxCalculateBo.setHouseTotal(Double.parseDouble(aet_house_total.getText().toString()));
        taxCalculateBo.setLevyType(levyType);
        taxCalculateBo.setOriginPrice(aet_house_original.getText().length() > 0 ?
                Double.parseDouble(aet_house_original.getText().toString()) : 0);
        taxCalculateBo.setBuyYear(buyYear);
        if (sc_buyer_first.isChecked()) {
            taxCalculateBo.setBuyerFirst(true);
        } else {
            taxCalculateBo.setBuyerFirst(false);
        }

        if (sc_seller_only.isChecked()) {
            taxCalculateBo.setSellerOnly(true);
        } else {
            taxCalculateBo.setSellerOnly(false);
        }
        taxCalculateCallback.callBack(taxCalculateBo);

    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_house_type:
                if (houseTypeDialog == null) {
                    houseTypeDialog = new AlertDialog.Builder(getContext())
                            .setTitle(R.string.calc_house_type)
                            .setSingleChoiceItems(houseTypes, 0, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    houseType = which + 1;
                                    atv_house_type.setText(houseTypes[which]);
                                    houseTypeDialog.dismiss();
                                }
                            }).create();
                }
                houseTypeDialog.show();
                break;
            case R.id.rl_levy_type:
                if (levyTypeDialog == null) {
                    levyTypeDialog = new AlertDialog.Builder(getContext())
                            .setTitle(R.string.calc_levy_type)
                            .setSingleChoiceItems(levyTypes, 0, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    levyType = which + 1;
                                    atv_levy_type.setText(levyTypes[which]);
                                    if (which == 1) {
                                        rl_house_original.setVisibility(View.VISIBLE);
                                    } else {
                                        rl_house_original.setVisibility(View.GONE);
                                    }
                                    levyTypeDialog.dismiss();
                                }
                            }).create();
                }
                levyTypeDialog.show();
                break;
            case R.id.rl_buy_years:
                if (buyYearsDialog == null) {
                    buyYearsDialog = new AlertDialog.Builder(getContext())
                            .setTitle(R.string.calc_buy_years)
                            .setSingleChoiceItems(buyYears, 2, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    buyYear = which;
                                    atv_buy_years.setText(buyYears[which]);
                                    buyYearsDialog.dismiss();
                                }
                            })
                            .create();
                }
                buyYearsDialog.show();
                break;
            default:
                break;
        }
    }

}

